<template>
	<div class="login-container">
		<el-form ref="theForm" :model="loginForm" :rules="loginRules" class="login-form">
			<h3 class="title">用户登录</h3>
			<el-form-item prop="name"><el-input :prefix-icon="User" v-model="loginForm.name" placeholder="输入用户名" tabindex="1" autocomplete /></el-form-item>
			<el-form-item prop="password">
				<el-input
					:prefix-icon="Key"
					show-password
					v-model="loginForm.password"
					type="password"
					placeholder="输入密码"
					tabindex="2"
					autocomplete
					@keyup.enter.native="handleLogin"
				/>
			</el-form-item>

			<el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">Login</el-button>

			<div class="tips">
				<span>name: admin</span>
				<span>password: 123456</span>
			</div>
		</el-form>
	</div>
</template>

<script setup>
import { User, Key } from '@element-plus/icons-vue';
import { ref, reactive, watch } from 'vue';
import { useRoute , useRouter} from 'vue-router';
import { useStore } from "vuex"
const router = useRouter();
const route = useRoute();
const store = useStore();
const loginForm = reactive({
	name: 'admin',
	password: '123456'
});

const loginRules = reactive({
	name: [{ required: true, trigger: 'blur' }],
	password: [{ required: true, trigger: 'blur' }]
});

const loading = ref(false);
const redirect = ref(undefined);

watch(
	route,
	newValue => {
		redirect.value = newValue.query && newValue.query.redirect;
	},
	{ immediate: true }
);

const theForm = ref(null);
const handleLogin = () => {
	theForm.value.validate(async valid => {
		if (valid) {
			loading.value = true;
			let result = await store.dispatch('user/login', loginForm);
			console.log(result);
			router.push({ path: redirect.value || '/' });
			loading.value = false;
		} else {
			console.log('登录表单数据校验错误');
			return false;
		}
	});
};
</script>

<style lang="scss" scoped>
/* 注意：自动填充时 input 背景不协调 和光标变色 */
$bg: #2d3a4b;
$title-color: #fff;
.login-container {
	height: 100vh;
	width: 100vw;
	background-color: $bg;
	overflow: hidden;
}
.login-form {
	position: relative;
	width: 520px;
	max-width: 100%;
	padding: 160px 35px 0;
	margin: 0 auto;
	overflow: hidden;
}

.tips {
	font-size: 14px;
	color: $title-color;
	margin: 30px 0px;

	span {
		&:first-of-type {
			margin-right: 16px;
		}
	}
}

.title {
	font-size: 26px;
	color: $title-color;
	margin: 0px auto 40px auto;
	text-align: center;
	font-weight: bold;
}
</style>
